<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Edit, Delete, Plus, Refresh } from '@element-plus/icons-vue'
import * as careContentApi from '@/api/careContent'

// 表格数据
const tableData = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formType = ref('add') // 'add' | 'edit'
// 表单验证规则
const formRules = reactive({
  name: [
    { required: true, message: '请输入护理项名称', trigger: 'blur' },
    { max: 50, message: '名称长度不能超过50个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择护理类型', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  duration: [
    { required: true, message: '请输入预计时长', trigger: 'blur' },
    { type: 'number', min: 1, message: '时长必须大于0', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入收费标准', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能为负数', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ],
  required_skills: [
    { max: 100, message: '技能描述长度不能超过100个字符', trigger: 'blur' }
  ]
})
// 表单引用
const formRef = ref(null)
// 分页参数
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  type: null,
  status: null
})

// 表单数据
const formData = reactive({
  careItemId: null,
  name: '',
  description: '',
  duration: 0,
  type: 1,
  price: 0,
  status: 1,
  frequency: 0,
  difficulty: 1,
  required_skills: ''
})

// 护理类型选项
const careTypes = [
  { value: 1, label: '基础护理' },
  { value: 2, label: '康复护理' },
  { value: 3, label: '心理护理' },
  { value: 4, label: '医疗护理' },
  { value: 5, label: '生活照料' }
]

// 状态选项
const statusOptions = [
  { value: 0, label: '禁用' },
  { value: 1, label: '启用' }
]

// 频率选项
const frequencyOptions = [
  { value: 0, label: '按需' },
  { value: 1, label: '每日' },
  { value: 2, label: '每周' },
  { value: 3, label: '每月' }
]

// 难度选项
const difficultyOptions = [
  { value: 1, label: '简单' },
  { value: 2, label: '中等' },
  { value: 3, label: '复杂' },
  { value: 4, label: '高难度' }
]

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      pageNo: pagination.current,
      pageSize: pagination.size
    }
    const res = await careContentApi.page(params)
    tableData.value = res.data.records || []
    pagination.total = res.data.total
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: null,
    status: null
  })
  handleSearch()
}

// 分页变化
const handlePageChange = (val) => {
  pagination.current = val
  loadData()
}

// 打开新增对话框
const handleAdd = () => {
  formType.value = 'add'
  dialogTitle.value = '新增护理任务'
  resetForm()
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  formType.value = 'edit'
  dialogTitle.value = '编辑护理任务'
  try {
    const res = await careContentApi.findById(row.careItemId)
    Object.assign(formData, res.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除护理任务 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await careContentApi.deleteById(row.careItemId)
      ElMessage.success('删除成功')
      loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    careItemId: null,
    name: '',
    description: '',
    duration: 0,
    type: 1,
    price: 0,
    status: 1,
    frequency: 0,
    difficulty: 1,
    required_skills: ''
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate()
    
    // 提交数据
    await careContentApi.save(formData)
    ElMessage.success(formType.value === 'add' ? '新增成功' : '更新成功')
    dialogVisible.value = false
    loadData()
  } catch (error) {
    if (error instanceof Error) {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
    // 验证失败时不显示错误消息
  }
}
// 获取类型标签颜色
const getTypeTagColor = (type) => {
  const colorMap = {
    1: 'plain',           // 基础护理 - 默认灰色
    2: 'success',    // 康复护理 - 绿色
    3: 'warning',    // 心理护理 - 黄色
    4: 'danger',     // 医疗护理 - 红色
    5: 'primary'     // 生活照料 - 蓝色
  }
  return colorMap[type] || 'plain'
}
// 初始化加载数据
onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="护理项名称" class="search-item">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入护理项名称"
            clearable
            style="width: 220px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="护理类型" class="search-item">
          <el-select
            v-model="searchForm.type"
            placeholder="全部类型"
            clearable
            style="width: 160px"
          >
            <el-option
              v-for="item in careTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" class="search-item">
          <el-select
            v-model="searchForm.status"
            placeholder="全部状态"
            clearable
            style="width: 120px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item class="search-item">
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
   <el-form-item style="margin-left: auto;">
  <el-button type="primary" :icon="Plus" @click="handleAdd" class="add-btn">
    新增护理任务
  </el-button>
</el-form-item>
      </el-form>
    </div>



    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        height="calc(100vh - 280px)"
      >
        <el-table-column prop="careItemId" label="护理任务编号" min-width="30" />
        <el-table-column prop="name" label="护理项名称" min-width="60" />
        <el-table-column prop="description" label="描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="类型" width="100" align="center">
            
  <template #default="{ row }">
    <el-tag :type="getTypeTagColor(row.type)">
      {{ careTypes.find(item => item.value === row.type)?.label || row.type }}
    </el-tag>
  </template>
</el-table-column>

<el-table-column label="执行频率" width="100" align="center">
<template #default="{ row }">
  <span>
    {{ ['按需', '每日', '每周', '每月'][row.frequency] || row.frequency }}
  </span>
</template>
</el-table-column>

<el-table-column label="操作难度" width="100" align="center">
  <template #default="{ row }">
    <span>
    {{ ['简单', '中等', '复杂', '高难度'][row.difficulty - 1] || row.difficulty }}
  </span>
  </template>
</el-table-column>

        <el-table-column prop="duration" label="时长(分钟)" width="100" align="center" />
        <el-table-column prop="price" label="价格(元)" width="100" align="center">
          <template #default="{ row }">
            {{ row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="230" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" :icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="loadData"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form 
      ref="formRef"
      :model="formData" 
      :rules="formRules"
      label-width="120px" 
      style="padding-right: 30px;"
    >
      <el-form-item label="护理项名称" prop="name" required>
        <el-input v-model="formData.name" placeholder="请输入护理项名称" />
      </el-form-item>
      <el-form-item label="护理项描述" prop="description" width='100px'>
        <el-input v-model="formData.description" type="textarea" placeholder="请输入护理项描述" />
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="护理类型" prop="type" required>
            <el-select v-model="formData.type" style="width: 100%">
              <el-option
                v-for="item in careTypes"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status" required>
            <el-select v-model="formData.status" style="width: 100%">
              <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="预计时长(分钟)" prop="duration" required>
            <el-input-number 
              v-model="formData.duration" 
              :min="1" 
              :step="5" 
              style="width: 100%" 
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收费标准(元)" prop="price" required>
            <el-input-number 
              v-model="formData.price" 
              :min="0" 
              :precision="2" 
              style="width: 100%" 
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="执行频率" prop="frequency">
            <el-select v-model="formData.frequency" style="width: 100%">
              <el-option
                v-for="item in frequencyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="操作难度" prop="difficulty">
            <el-select v-model="formData.difficulty" style="width: 100%">
              <el-option
                v-for="item in difficultyOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="所需技能" prop="required_skills">
        <el-input 
          v-model="formData.required_skills" 
          placeholder="请输入所需技能，多个技能用逗号分隔" 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
  </div>
</template>

<style scoped>
/* 整体容器 */
.care-task-container {
  padding: 20px;
  background-color: #f8fafc;
  min-height: calc(100vh - 40px);
}

/* 搜索区域 */
.search-section {
  padding: 16px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.search-item {
  margin-bottom: 0;
  margin-right: 16px;
}

.search-item :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

/* 工具栏区域 */
.toolbar-section {
  padding: 16px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.add-btn {
  height: 36px;
  padding: 0 20px;
  border-radius: 8px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
  transition: all 0.3s;
}

.add-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 表格区域 */
.table-section {
  padding: 16px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

/* 表格样式 */
.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f8fafc;
  --el-table-row-hover-bg-color: #f5f7fa;
  font-size: 14px;
}

.el-table :deep(th) {
  font-weight: 600;
  color: #303133;
  background-color: #f8fafc !important;
}

.el-table :deep(.el-table__row) {
  transition: background-color 0.2s;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

/* 标签样式 */
.el-tag {
  border-radius: 4px;
  font-weight: 500;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

/* 类型标签特殊样式 */
.el-tag.el-tag--plain {
  background-color: #f3e8ff;
  border-color: #d8b4fe;
  color: #8b5cf6;
}

.el-tag.el-tag--success {
  background-color: #f0fdf4;
  border-color: #86efac;
  color: #16a34a;
}

.el-tag.el-tag--danger {
  background-color: #fef2f2;
  border-color: #fca5a5;
  color: #dc2626;
}

/* 分页样式 */
.pagination-wrapper {
  padding: 16px 0;
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 按钮样式 */
.el-button {
  border-radius: 8px;
  padding: 8px 16px;
  transition: all 0.2s;
}

/* 对话框样式调整 */
:deep(.el-dialog) {
  border-radius: 12px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 16px 20px;
  background-color: #f8fafc;
  border-bottom: 1px solid #ebeef5;
  margin-right: 0;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #333;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background-color: #f8fafc;
  border-top: 1px solid #ebeef5;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-item {
    margin-right: 0;
    margin-bottom: 12px;
    width: 100%;
  }
  
  .search-item :deep(.el-input),
  .search-item :deep(.el-select) {
    width: 100% !important;
  }
  
  .add-btn {
    width: 100%;
    margin-top: 12px;
  }
  
  .el-table {
    height: auto !important;
  }
}
</style>